import requests
import json
import time
import xlwt

#台风信息
number = [] #台风编号
name = [] #台风中文名
nameE = [] #台风英文名

Year=[2020,2021]
#year = input("输入台风的年份") # 输入台风的年份
#Python爬虫天气预报（小白入门） | Coder·码农网  https://www.codercto.com/a/9087.html
#含时间戳的url，请求头

for index in range(len(Year)):
    year=str(Year[index])

    url = "http://d1.weather.com.cn/typhoon/typhoon_list/list_"+year+".json?callback=getData&_="+str(int(round((time.time()*1000))))
    headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
            "Referer": "http://typhoon.weather.com.cn/gis/typhoon_p.shtml",
        }
    r = requests.get(url,headers=headers)
    print(r.text)
    a = json.loads(r.text[8:-1])#解析json文件   //去除前面的八个字符
    print(a["typhoonList"])
    print(len(a["typhoonList"]))


    #print(a["typhoon"][8][21])
    for i in range(len(a["typhoonList"])):
        b = a["typhoonList"][i]
        print(b[0],b[1],b[2])
        number.append(a["typhoonList"][i][0])
        name.append(a["typhoonList"][i][2])
        nameE.append(a["typhoonList"][i][1])


    f = xlwt.Workbook() #创建工作簿
    sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) #创建sheet,存放台风编号和名称
    j=0

    for number1,name1,nameE1\
         in zip(number,name,nameE):
        sheet1.write(j,0,number1);sheet1.write(j,1,name1);sheet1.write(j,2,nameE1);
        j = j+1
    f=f
f.save("F:\台风编号信息.xls")#保存文件，文件名每一个台风更换不同的名称，我这里是以台风编号命名的。这个路径自己设定






